
package com.netcracker.ui.command;

import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.UserService;
import com.netcracker.util.service.exception.DataTransmittingException;
import com.netcracker.util.service.exception.WrongUserException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;

public class ChangeUserPasswordCommand implements Command {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChangeUserPasswordCommand.class);
    private final ServiceFacade serviceFacade;

    public ChangeUserPasswordCommand(ServiceFacade serviceFacade) {
        this.serviceFacade = serviceFacade;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        String currentLogin = (String) request.getSession().getAttribute("user");
        String username = request.getParameter("username");
        if (currentLogin.equals(username)) {
            String newPassword = request.getParameter("newPassword");
            String oldPassword = request.getParameter("oldPassword");
            UserService userService = serviceFacade.getUserService();
            try {
                userService.changeUserPassword(username, newPassword, oldPassword);
                return "profile.jsp";
            } catch (DataTransmittingException ex) {
                request.setAttribute("error", "Ошибка обращения к БД.");
                LOGGER.error("DB error:", ex);
                return "index.jsp";
            } catch (NoSuchAlgorithmException ex) {
                request.setAttribute("error", "Произошла ошибка. Повторите попытку позже.");
                return "index.jsp";
            } catch (WrongUserException ex) {
                request.setAttribute("error", "Пароль веден неверно.");
                return "UserProfile.jsp";
            }
        } else {
            request.setAttribute("error", "Недостаточно прав на изменение пароля.");
            return "index.jsp";
        }
    }
    
}
